#include "dynamic_json_ui/dynamic_json_ui.h"

#include <QLabel>
#include <QLineEdit>
#include <QComboBox>
#include <QTextEdit>
#include <QPushButton>
#include <QCheckBox>
#include <QRadioButton>
#include <QSlider>
#include <QSpinBox>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFile>
#include <QTextStream>
#include <QDebug>

#include "dynamic_json_ui/json_parser.h"
#include "dynamic_json_ui/widget_factory.h"
#include "dynamic_json_ui/widget_registry.h"

namespace dynamic_json_ui {

DynamicJsonUI::DynamicJsonUI(QWidget *parent) : QWidget(parent)
{
}

void DynamicJsonUI::loadFromJsonString(const QString &jsonStr)
{
    JsonUiElement root = JsonParser::parse(jsonStr);

    QWidget *content = WidgetFactory::createWidget(root, this);
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(content);
    setLayout(layout);

    if (!root.style.isEmpty()) {
        this->setStyleSheet(root.style);
    }
}

void DynamicJsonUI::loadFromJsonFile(const QString &filePath)
{
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "无法打开文件：" << filePath;
        return;
    }
    QString content = QTextStream(&file).readAll();
    loadFromJsonString(content);
}

void DynamicJsonUI::setPropertyValue(const QString &id, const QString &property,
                                     const QVariant &value)
{
    QWidget *widget = WidgetRegistry::instance().getWidget(id);
    if (!widget)
        return;

    if (property == "text") {
        if (QLabel *label = qobject_cast<QLabel *>(widget))
            label->setText(value.toString());
        else if (QPushButton *btn = qobject_cast<QPushButton *>(widget))
            btn->setText(value.toString());
        else if (QLineEdit *le = qobject_cast<QLineEdit *>(widget))
            le->setText(value.toString());
        else if (QTextEdit *te = qobject_cast<QTextEdit *>(widget))
            te->setPlainText(value.toString());
    } else if (property == "placeholderText") {
        if (QLineEdit *le = qobject_cast<QLineEdit *>(widget))
            le->setPlaceholderText(value.toString());
    } else if (property == "checked") {
        if (QCheckBox *cb = qobject_cast<QCheckBox *>(widget))
            cb->setChecked(value.toBool());
        else if (QRadioButton *rb = qobject_cast<QRadioButton *>(widget))
            rb->setChecked(value.toBool());
    } else if (property == "currentIndex") {
        if (QComboBox *cb = qobject_cast<QComboBox *>(widget))
            cb->setCurrentIndex(value.toInt());
    } else if (property == "value") {
        if (QSlider *slider = qobject_cast<QSlider *>(widget))
            slider->setValue(value.toInt());
        else if (QSpinBox *spin = qobject_cast<QSpinBox *>(widget))
            spin->setValue(value.toInt());
    } else if (property == "style") {
        widget->setStyleSheet(value.toString());
    }
}

} // namespace dynamic_json_ui
